import commonEvent from '@ohos.commonEvent';
import { initInfo } from "./log";
const TAG = "commonEvent-utilslib"
let log = initInfo(TAG);

export class ComEvent{
    public subscribeInfo = { events: [] }
    public subscriber = null;

    constructor(events: string[], callback) {
        this.subscribeInfo.events = events;

        commonEvent.createSubscriber(this.subscribeInfo, (err, commonEventSubscriber)=>{
            if(err.code){
                log(`createSubscriber faile err: ${JSON.stringify(err)}`);
            }else{
                log(`createSubscriber success`);
                this.subscriber = commonEventSubscriber;
                this.subscribe(callback)
            }
        });
    }

    subscribe(callback){
        log(`subscribe`);
        if(this.subscriber){
            log(`subscriber ready`);
            commonEvent.subscribe(this.subscriber, callback);
        } else {
            log(`no subscriber`);
        }
    }

    unsubscribe(callback?){
        let fun = (err)=>{
            if(err.code){
                log(`unsubscribe failed: ${JSON.stringify(err)}`);
            }else{
                log(`unsubscribe success`)
            }
        }
        if(callback){
            fun = callback
        }
        if(this.subscriber){
            log(`subscriber ready`);
            commonEvent.unsubscribe(this.subscriber, fun);
        } else {
            log(`no subscriber`);
        }
    }
}